package com.mhkj.base.fruitType.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.mhkj.base.fruitType.entity.FruitType;
import com.mhkj.base.fruitType.repository.FruitTypeRepository;
import com.mhkj.base.fruitType.service.FruitTypeService;
import com.mhkj.base.templete.entity.PlanTemplete;
import com.mics.core.common.componet.Pagination;
import com.mics.core.system.base.service.impl.BaseServiceImpl;

/**
 * 成果类别
 * @author mics
 * @date 2018年8月9日
 * @version 1.0
 */
@Service
public class FruitTypeServiceImpl extends BaseServiceImpl<FruitType> implements FruitTypeService{
	@Resource
	private FruitTypeRepository fruitTypeRepository;

	@Resource
	public void setFruitTypeRepository(FruitTypeRepository fruitTypeRepository) {
		super.setBaseRepository(fruitTypeRepository);
	}

	@Override
	public FruitType getByTempleteAndName(PlanTemplete planTemplete,
			String nodeName) {
		return fruitTypeRepository.getByTempleteAndName(planTemplete.getId(),nodeName);
	}

	@Override
	public Pagination<FruitType> listByPage(FruitType fruitType, int pageIndex,
			int pageSize) {
		Specification<FruitType> specification = new Specification<FruitType> () {  
			/**
			 * 序列号
			 */
			private static final long serialVersionUID = -786003485941679959L;
			@Override
			public Predicate toPredicate(Root<FruitType> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
               List<Predicate> lstPredicates = new ArrayList<Predicate>();
               if(StringUtils.isNoneBlank(fruitType.getName())){
                   Predicate p1=criteriaBuilder.like(root.get("name").as(String.class), "%"+fruitType.getName()+"%");
                   lstPredicates.add(p1);
               }
              Predicate[] arrayPredicates = new Predicate[lstPredicates.size() ];
              return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
	        } };
		Page<FruitType> pageT =  fruitTypeRepository.findAll(specification, PageRequest.of(pageIndex, pageSize, Sort.Direction.ASC,"name"));
		Pagination<FruitType> pagination = new Pagination<FruitType>();
		pagination.setTotal(fruitTypeRepository.count(specification));
		pagination.setData(pageT.getContent());
		return pagination;
	}

	@Override
	public FruitType getByNodeResult(long nodeResult) {
		return fruitTypeRepository.getByNodeResult(nodeResult);
	}

	
}
